package com.fatgirl.patterns.state.fusm
{
	import com.fatgirl.patterns.iterator.IIterator;
	import com.fatgirl.patterns.state.IStateControl;

	/**
	 *  
	 * 模糊状态机
	 * @author iceman
	 * 
	 */
	public class FuSMStateMachine extends AbsFuSMState
	{
		private var m_states:Vector.<IFuSMState>;//状态列表
		private var m_activatedStates:Vector.<IFuSMState>;//活动状态列表
		public function FuSMStateMachine(_type:int,_controller:IStateControl = null)
		{
			super(_type,_controller);
			m_states = new Vector.<IFuSMState>;
			m_activatedStates = new Vector.<IFuSMState>;
		}
		/**
		 * 添加状态 
		 * @param _state 状态对象
		 * 
		 */
		public override final function addItem(_state:IFuSMState):void
		{
			_state.setParent(this);
			m_states.push(_state);
		}
		/**
		 * 更新状态机 
		 * 
		 */
		public override final function updateMachine():void
		{
			if(m_states.length == 0)
			{
				return;
			}
			m_activatedStates.length = 0;
			var t_nonActiveStates:Vector.<IFuSMState> = new Vector.<IFuSMState>;
			for(var i:int =0;i<m_states.length;i++)
			{
				if(m_states[i].calculateActivation() > 0)
				{
					m_activatedStates.push(m_states[i]);
				}
				else
				{
					t_nonActiveStates.push(m_states[i]);
				}
			}
			
			//不活动列表 退出
			if(t_nonActiveStates.length != 0)
			{
				for(i =0;i<t_nonActiveStates.length;i++)
				{
					t_nonActiveStates[i].exit();
				}
			}
			
			//更新活动状态
			if(m_activatedStates.length != 0)
			{
				for(i =0;i<m_activatedStates.length;i++)
				{
					m_activatedStates[i].update();
				}
			}
			
		}//end fun
		
		/**
		 * 重置所有状态 
		 * 
		 */
		public override final function reset():void
		{
			//退出 init 所有状态
			for(var i:int =0;i<m_states.length;i++)
			{
				m_states[i].exit();
				m_states[i].init();
			}
		}
		/**
		 * 是否是活动状态 
		 * @param _state 状态
		 * @return 返回true或者false
		 * 
		 */
		public override final function isActive(_state:IFuSMState):Boolean
		{
			for(var i:int = 0 ; i<m_activatedStates.length;i++)
			{
				if(m_activatedStates[i] == _state)
				{
					return true;
				}
			}
			return false;
		}
		/**
		 * 返回一个子状态迭代器 
		 * @param _type 目前对类型不做处理
		 * @return 
		 * 
		 */
		public override final function iterator(_type:String=null):IIterator
		{
			return new FuSMStateIterator(m_states);
		}
			
	}//end class
}